// src/api/auth.js
import axios from 'axios';
import { useAuthStore } from '@/stores/auth';

const _authAxios = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api',
    headers: {
        'Content-Type': 'application/json'
    }
});

// 请求拦截器：强制附加 Token
_authAxios.interceptors.request.use(config => {
    const token = localStorage.getItem('accessToken');
    console.debug('[Request Interceptor]', `URL: ${config.url}`, `Token exists: ${!!token}`);

    if (token && !config.skipAuth) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
}, error => {
    console.error('[Request Interceptor Error]', error);
    return Promise.reject(error);
});

// 响应拦截器：处理 401 自动刷新 Token
_authAxios.interceptors.response.use(
    response => {
        console.debug('[Response Interceptor]', `URL: ${response.config.url}`, 'Status:', response.status);
        return response;
    },
    async error => {
        const originalRequest = error.config;
        const authStore = useAuthStore();

        console.error('[Response Interceptor Error]', `URL: ${originalRequest?.url}`, 'Status:', error.response?.status);

        // 处理 401 且未重试过的请求
        if (error.response?.status === 401 && !originalRequest._retry) {
            const refreshToken = localStorage.getItem('refreshToken');
            if (!refreshToken) {
                console.error('无有效的刷新令牌');
                await authStore.logout();
                return Promise.reject(new Error('登录已过期，请重新登录'));
            }

            originalRequest._retry = true;
            try {
                console.debug('尝试刷新 AccessToken...');
                await authStore.refreshAccessToken();
                const newToken = localStorage.getItem('accessToken');
                originalRequest.headers.Authorization = `Bearer ${newToken}`;
                return _authAxios(originalRequest);
            } catch (refreshError) {
                console.error('刷新令牌失败:', refreshError);
                await authStore.logout();
                return Promise.reject(refreshError);
            }
        }
        return Promise.reject(error);
    }
);

// 显式设置/清除认证头
const setAuthHeader = (token) => {
    if (token) {
        _authAxios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    } else {
        delete _authAxios.defaults.headers.common['Authorization'];
    }
    console.debug('Auth header updated:', !!token);
};

// API 方法
export const authApi = {
    login: (credentials) => _authAxios.post('/auth/login', credentials, { skipAuth: true }),
    getCurrentUser: () => _authAxios.get('/auth/me'),
    refreshToken: (refreshToken) => _authAxios.post('/auth/refresh', { refreshToken }, { skipAuth: true }),
    logout: () => _authAxios.post('/auth/logout'),
    setAuthHeader
};

export default authApi;
export const authAxios = _authAxios; // 恢复这一行导出